
#include "../include/files.h"

oal::files::files() {
}

oal::files::~files() {
}

/**
 * Open a file direct from the instance with the mode r,w,a read,write,append
 *
 * @param	string	filename to open
 * @param	string	method values = r - read, w - write, a - append
 *
 */
oal::files::files(string newFilename, string method) {
	this->filename = newFilename;
	this->method = method;
	if(!method.empty()) {
		if(method == "r") {
			this->openFile.open(this->filename.c_str(), ios::in | ios::binary);
		}
		if(method == "w") {
			this->openFile.open(this->filename.c_str(), ios::out | ios::binary);
		}
		if(method == "a") {
			this->openFile.open(this->filename.c_str(), ios::app | ios::binary);
		}
	}
}

/**
 * Checks the file by the open filename if there exists on
 * the disk
 *
 * @return	boolean		true if the file is exists,
 * 						false otherwise
 */
bool oal::files::isFile(void) {
	bool result = false;
	struct stat attribut;
	if(stat(this->filename.c_str(), &attribut) != -1) {
		if(attribut.st_mode & S_IFREG) {
			result = true;
		}
	}
	return result;
}

/**
 * Deletes an file from the diskspace
 *
 * @retrun	boolean	true if the file successful delete,
 * 					otherwise false
 */
bool oal::files::erase(void) {
	bool result = false;
#ifdef _WIN32
	result = (_unlink(this->filename.c_str()) == 0);
#else
	result = (unlink(this->filename.c_str()) == 0);

#endif
	return result;
}

/**
 * Returns true if the files is successful opened
 *
 * @return	boolean	true if the file is open,
 * 					false otherwise
 */
bool oal::files::is(void) {
	return !this->openFile.bad();
}

/**
 * Gets the content from the open file
 *
 * @param	*string	content of the open file
 */
string oal::files::getContent(void) {
string result = "";
	if(!this->openFile.bad()) {
		if(this->openFile.tellg() > -1) {
			this->openFile.seekg(0, ios::end);
			vector<char> *buffer = new vector<char>(this->openFile.tellg());
			this->openFile.seekg(0, ios::beg);
			this->openFile.read(&(*buffer)[0], (*buffer).size());
			string *resultInIs = new string((*buffer).begin(), (*buffer).end());
			result = (*resultInIs);
			delete resultInIs;
			delete buffer;
		} else {
			throw noFileExists();

		}
		this->openFile.close();
	}
	return result;
}

/**
 * Puts the given content into the open file
 *
 * @param	string	content to put into files
 */
bool oal::files::putContent(std::string content) {
	bool result = false;
	if(!this->openFile.bad() || this->method == "w") {
		result = this->openFile.write(content.c_str(),content.length());
		this->openFile.close();
	}
	return result;
}

/**
 * Gets the lines from stdin
 *
 * @return	string	content from stdin
 */
std::string oal::files::getFromStdin() {
	std::string result="";
	while(!std::cin.eof() > 0) {
		result += std::cin.get();
	}
	return result;
}
